<template>
  <el-dialog
    :title="title"
    :model-value="true"
    width="60%"
    @close="backOff"
    :modal="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    center
  >
    <el-form
      :model="data"
      ref="from"
      :rules="rules"
      label-position="left"
      label-width="`100%`"
      style="padding: 0 40px"
    >
      <el-form-item prop="name" label="name:" :label-width="`80px`">
        <el-input v-model="data.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="age" label="age:" :label-width="`80px`">
        <el-input v-model.number="data.age" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="backOff">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, PropType, toRaw, toRefs, ref, reactive } from 'vue'
import { useItem, useList } from '../model/useModel'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
  props: {
    isEdit: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    title: {
      type: String as PropType<string>,
      default: '操作'
    }
  },
  setup(props) {
    const { getItem, itemData, updateItem, createItem } = useItem()

    const route = useRoute()
    const id = route.params.id as string
    props.isEdit && getItem(id)

    const rules = toRaw({
      name: [
        { required: true, message: '用户名为必填项', trigger: 'change' }
      ],
      age: [
        { required: true, message: '年龄为必填项', trigger: 'change' },
        { type: 'number', message: '年龄为数字', trigger: 'change' }
      ]
    })

    const router = useRouter()
    const backOff = () => router.replace('/user')

    const from = ref<any>(null)
    const { updateList } = useList()
    const handleSubmit = () => {
      from.value.validate((valid: boolean) => {
        if (valid) {
          props.isEdit ? updateList(updateItem(id)) : updateList(createItem())
          backOff()
        }
      })
    }

    return { ...toRefs(itemData), handleSubmit, rules, backOff, from }
  }
})
</script>
